package org.example.rabbitmq;

import com.hivemq.client.mqtt.datatypes.MqttQos;
import com.hivemq.client.mqtt.mqtt3.Mqtt3AsyncClient;
import com.hivemq.client.mqtt.mqtt3.Mqtt3Client;

import java.nio.charset.StandardCharsets;

public class MqttPublisher {

    public static void main(String[] args) {
        // RabbitMQ MQTT 地址和端口
        String host = "192.168.0.227";
        int port = 1883;

        // MQTT 主题和消息内容
        String topic = "test/topic";
        String message = "Hello from Java MQTT client!";

        // 创建客户端 ID（可随机）
        String clientId = "JavaMqttClient";

        // 构建并连接客户端
        Mqtt3AsyncClient client = Mqtt3Client.builder()
                .identifier(clientId)
                .serverHost(host)
                .serverPort(port)
                .buildAsync();

        // 建立连接

        client.connectWith()
                .simpleAuth()
                .username("mq")
                .password("123456".getBytes(StandardCharsets.UTF_8))
                .applySimpleAuth()
                .send()
                .whenComplete((connAck, throwable) -> {
                    if (throwable != null) {
                        System.err.println("Connection failed: " + throwable);
                    }
                })
                .toCompletableFuture()
                .join(); // 使用 Mqtt3AsyncClient 的 connect 方法
        System.out.println("Connected to RabbitMQ MQTT broker");

        // 发布消息
        client.publishWith()
                .topic(topic)
                .payload(message.getBytes(StandardCharsets.UTF_8))
                .qos(MqttQos.AT_LEAST_ONCE)
                .send()
                .join();

        System.out.println("Message sent: " + message);
    }
}
